package com.lanou3g.exam.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUitl {
    private static ThreadLocal<Connection> threadLocal
            = new ThreadLocal<>();


    public static final String USER = "root";
    public static final String PASSWORD = "123456";
    public static final String URL = "jdbc:mysql://localhost:3306/lanou_user";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");//官方固定写法,注册驱动
            //当调用这个JDBCUitl类时,这个静态代码块里的代码会自动的执行,即会自动的执行
            //这个代码,Driver也就被调用了,java封装了Driver的方法,在那里面他已经new了,所以
            //这块这样写就行,不需要再new一遍
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeConn() {
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                if (!conn.getAutoCommit()){
                //如果开启了事务,那么提交事务
                conn.commit();
            }
                conn.close();
                //把这个conn从threadLocal中清楚
                threadLocal.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void begin(){
        Connection conn=getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        try {

            Connection conn = threadLocal.get();
            if (conn == null) {
                conn = DriverManager.getConnection(URL, USER, PASSWORD);
                threadLocal.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);//为什么改成抛异常,因为当异常的时候,
            //你的返回值就会为空,而且不报错,所以在这儿抛异常,让程序崩掉
        }
    }
}
